#!/usr/bin/env node
/**
 * Created by udi on 17-7-14.
 */
'use strict';

var program = require('commander');

var fs = require("./util/async_file")
var jv = require("./util/jv")
var path = require('path');
var watch = require('node-watch');
var packjson = require("./package.json");
//var exec = require('child_process').exec;
var print = function (msg) {
  if (!msg) return;
  process.stdout.write("[" + ( new Date().toString() ) + "]" + msg);
}
// const {rmdir} = require('commandir')
//var fs = require("fs")

var cmd = program
    .version(packjson.version)
    .description(packjson.description)
    .usage('<--source 源文件夹> <--file-type 文件类型> <--config 配置>')
    .option('--source <源文件夹>', "")
    .option('--clean [是否清除]', "清除目标文件夹内容")
    .option('--target [目标文件夹]', "\n" +
        "\t\t如果为空，则等于 source。 \n" +
        "\t\t如果 source 是以 lang结尾，则 target 用语言代码替换结尾的 lang。")
    .option('--file-type <文件类型>', '如：-f js,css')
    .option('-c, --config <配置>', '使用伪Json格式，key表示tagName,value表示语言代码。如：-c c:cn,e:en')
    .option('-l, --language [当前语言]', '仅编译当前语言，配置项的key值。')
    .option('-t, --template [target结尾的语言替换符]', '默认值为lang，会把结尾的lang替换为相应的语言值。')
    .option('-w, --watch [编译完后，继续监视]', '')
    .option('--define [定义的变量]', '模板中使用，如： 定义： --define test:"http://pinzhixin.cn",i:1 ， 使用：<<define-test>>')
    .parse(process.argv);

if (!cmd.fileType || !cmd.source || !cmd.config) {
  cmd.outputHelp();
  return -1;
}

if (!cmd.template) {
  cmd.template = "lang";
}

if (!cmd.target) {
  cmd.target = cmd.source;
}

cmd.source = path.resolve(cmd.source);
cmd.target = path.resolve(cmd.target);


var config = {};
cmd.config.split(",").forEach(it => {
  var sect = it.split(':');
  config[sect[0]] = sect[1];
});

var defineMap = {};

(cmd.define || "")
    .replace(",,", String.fromCharCode(7), "g")
    .split(",")
    .forEach(it => {
      var sects = it.replace(String.fromCharCode(7), ",", "g").split(":");
      //以第一个: 前面的做为 key , 后面的做为  value .
      defineMap[sects[0]] = sects.slice(1).join(":");
    });


var allTagNames = Object.keys(config);


var fileTypes = cmd.fileType.split(",");

var targetHead = cmd.target;
if (targetHead.endsWith(cmd.template)) {
  targetHead = targetHead.slice(0, 0 - cmd.template.length);
}

function getTarget(path, language) {
  var ret = targetHead + "_" + language + path.slice(cmd.source.length)
  return ret;
}


(async function () {
  if (jv.AsBool(cmd.clean)) {
    for (var i = 0, len = allTagNames.length; i < len; i++) {
      var tag = allTagNames[i];
      if (cmd.language && (cmd.language != tag)) continue;
      var target = getTarget("", config[tag]);

      if (fs.existsSync(target) == false) {
        // console.log("目标文件夹 " + target + " 不存在,已忽略清除")
        continue;
      }

      print(target + "\t")

      if (await jv.rm(target) == false) {
        console.log("清理出错！")
      }
      else {
        console.log(".");
      }
    }
  }


  //核函数。
  var handleFile = async function (path, isFile) {
    var content = null;
    var needTranslate = false;
    if (isFile) {
      content = await fs.readFileAsync(path, 'utf8');
      needTranslate = fileTypes.contains(it => path.endsWith("." + it));
    }

    for (var i = 0, len = allTagNames.length; i < len; i++) {
      var tag = allTagNames[i];
      if (cmd.language && (cmd.language != tag)) continue;

      var target = getTarget(path, config[tag]);
      if (isFile == false) {
        if (await jv.mkdirs(target) === false) {
          return false;
        }
        continue;
      }

      //处理 define.
      content = jv.procDefine(content, defineMap);

      if (needTranslate == false) {
        jv.copyFile(path, target)
        continue;
      }

      fs.writeFileSync(target, jv.procTagLang(content, allTagNames, tag));
    }
  }

  if (cmd.watch) {
    watch(cmd.source, {recursive: true}, function (evt, name) {
      print(evt + ':' + name);

      var stat = fs.statSync(name);


      for (var i = 0, len = allTagNames.length; i < len; i++) {
        var tag = allTagNames[i];
        if (cmd.language && (cmd.language != tag)) continue;

        var target = getTarget(name, config[tag]);
        if (evt == "remove") {
          if (fs.existsSync(target) == false) continue;
          jv.rm(target);
        }
        else {
          if (stat.isDirectory()) {
            if (fs.existsSync(target) == false) continue;
            jv.mkdirs(target)
          }
        }
      }

      if (evt == "update" && stat.isFile()) {
        handleFile(name, true);
      }

      console.log("\t\t(ok!)")
    });
  }

  print(cmd.source + "\t");
  //console.log("___________________________________________________________________")

  await jv.walkFile(cmd.source, handleFile);


  //console.log("¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯")
  console.log("编译完成!");
  return 0;
})();




